import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () => import('../components/login.vue')
  },
  {
    path: '/home',
    component: () => import('../components/home.vue'),
    redirect: '/welecome',
    children: [
      {
        path: '/users',
        component: () => import('../components/users.vue')
      },
      {
        path: '/welecome',
        component: () => import('../components/welecome.vue')
      },
      {
        path: '/roles',
        component: () => import('../components/roles.vue')
      },
      {
        path: '/rights',
        component: () => import('../components/rights.vue')
      },
      {
        path: '/goods',
        component: () => import('../components/goods.vue')
      },
      {
        path: '/add',
        component: () => import('../components/add.vue')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 判断是否登录
  if (sessionStorage.token) {
    // 如果sessionStorage中有token，证明登录过了
    next() // 放行
  } else {
    // 没有登录过
    if (to.path === '/login') {
      // 如果要访问登录页面
      next()
    } else {
      next('/login') // 如果没有登录，跳转到登录页面
    }
  }
})

export default router
